<template>
  <div class="home">
    <!-- <van-nav-bar :title="appName" /> -->
    <div class="chat-con">
      <div flex="main:left cross:center" class="btn-box">
        <van-button v-if="!openPre" plain type="primary" size="mini" @click="openPre = true">
          返 回
        </van-button>
        <van-button v-else plain type="primary" size="mini" @click="openPre = false">
          一键跳过
        </van-button>
      </div>
      <div flex="dir:top main:justify cross:center" class="chat-content">
        <ChatMsgNew
          v-if="isShowInputOrMsg"
          style="width: 100%"
          :shareId="shareId"
          :loading="loading"
          @tabChange="tabChange"
          @loadMore="loadMore"
        />
        <PresetQues
          v-if="openPre === true && preQueData.length > 0"
          :kbId="kbId"
          :preQueData="preQueData"
          @click="handleClick"
        />
      </div>
      <div class="chat-input-box">
        <ChatInputNew v-if="isShowInputOrMsg" />
      </div>
    </div>
  </div>
</template>

<script setup>
import { computed, ref, reactive } from 'vue'
import { useRoute } from 'vue-router'
import { chatInit, getSharePreQuesList } from '@/api/modules/home.api'
import { throwError } from '@/utils/util'
import { useUserStore } from '@/store/useUserStore'
import { sessionInit, curSession } from './app-chat/useChat'
import ChatMsgNew from './app-chat/ChatMsgNew.vue'
import ChatInputNew from './app-chat/ChatInputNew.vue'
import PresetQues from './app-chat/PresetQues.vue'
import { AUTH_TOKEN, SHARE_ID } from '@/config/token-const'

const userStore = useUserStore()

const route = useRoute()

const appName = ref('智能问答')
const kbId = ref('')
const openPre = ref(false)
const preQueData = ref([])
const shareId = ref('285c63dfd3204e2eaab0c6e1b489cf69')

// const visible = computed(() => openPre.value && preQueData.value.length > 0)

const isShowInputOrMsg = computed(() => {
  return openPre.value === false || (openPre.value === true && preQueData.value.length === 0)
})

const tabs = ref([])

const query = reactive({
  shareId: '',
  category: '',
  scCategory: '',
  question: '',
  startDate: '',
  endDate: '',
  knowledgeId: '',
  page: 1,
  size: 5,
})
const quesList = ref([]) // 问题列表
const total = ref(0)
const loading = ref(false)

async function getList() {
  try {
    const { total: t, rows } = await getSharePreQuesList(shareId.value, query)
    total.value = t
    quesList.value = rows
  } catch (error) {
    throwError('ChatView/getList', error)
  }
}

async function handleClick(category, scCategory) {
  query.category = category.id
  query.scCategory = scCategory.id
  query.knowledgeId = kbId.value
  openPre.value = false
  await getList()
  tabs.value = category.children.map(tab => {
    return {
      id: tab.id,
      title: tab.text,
      total: tab.id === scCategory.id ? total.value : 0,
      // 给选中的添加对应的问题列表
      quesList: tab.id === scCategory.id ? quesList.value : [],
    }
  })
  curSession.value.messages.push({
    role: 'assistant',
    content: '预设问题',
    isPreQue: true,
    activeTab: scCategory.id,
    tabs: tabs.value,
  })
}

async function initChat() {
  const code = route.query.code || '0319Yd1w3nvSr23zMr3w30IxJp49Yd15'
  await userStore.getUserInfo(code)

  // 将路由中携带的authToken和shareId存储起来
  // localStorage.setItem(AUTH_TOKEN, route.query.authToken)
  // localStorage.setItem(SHARE_ID, route.query.shareId)
  localStorage.setItem(SHARE_ID, shareId.value)

  try {
    // 页面初始话接口（拿到开场白、预设问题、应用名称）
    // const data = await chatInit(route.query.shareId)
    const data = await chatInit(shareId.value)
    appName.value = data?.applicationName // 应用名称
    openPre.value = data?.open_pre // 是否开启预设问题
    const confTypeItem = data?.confType?.[0]
    preQueData.value = confTypeItem?.children || []
    kbId.value = confTypeItem?.code || ''
  } catch (e) {
    throwError('Home/initChat', e)
  }
}

async function tabChange(tab) {
  query.scCategory = tab
  query.page = 1
  await getList()
  // 切换时将接口获取的问题追加到session消息对应的tab中
  console.log(tab)
  curSession.value.messages
    .find(obj => obj.activeTab === tab)
    .tabs.find(obj => obj.id === tab).quesList = quesList.value
  // console.log(curTabTabs);
  console.log(curSession.value.messages)
}

// 加载更多
async function loadMore(tab) {
  console.log(tab);
  loading.value = true
  if (tab.total > tab.quesList.length) {
    query.scCategory = tab.id
    query.page++
    await getList()
    curSession.value.messages
      .find(obj => obj.activeTab === tab.id)
      .tabs.find(obj => obj.id === tab.id)
      .quesList.push(...quesList.value)
  }
  loading.value = false
}

sessionInit()
initChat()
</script>

<style lang="stylus" scoped>
.home {
  height: 100%;
  box-sizing: border-box;
  .chat-con {
    display: flex;
    flex-direction: column;
    height: 100%
    background-color: #fff;
    box-sizing: border-box;
    .btn-box{
      padding 10px;
    }
    .chat-content {
      box-sizing border-box;
      padding 0 10px;
      width: 100%;
      height: calc(100% - 100px);
    }
    .chat-input-box{
      position absolute;
      bottom 0;
      left 0;
      right 0;
    }
  }
}
</style>
